<?php

namespace app\helpers;


use app\models\Admin;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\helpers\Console;

class InstallHelper {

    /**
     * @param $params
     * @return bool
     */
    public static function installSql($params) {
//        self::stdout('[+]: 安装数据库表.', Console::FG_GREEN);
//
//        $sqlFile = Yii::$app->runtimePath . '/install/mysql.sql';
//        $sql = file_get_contents($sqlFile);
//        $sql = explode(";", $sql);
//        foreach ($sql as $v) {
//            if (empty($v)) {
//                continue;
//            }
//            $v = str_replace('ii_', $params['db_prefix'], $v);
//            preg_match('#TABLE `([^`]+)`#i', $v, $match);
//            Yii::$app->db->createCommand($v)->execute();
//            if (isset($match[1])) {
//                self::stdout("数据表: {$match[1]} 执行成功.");
//            }
//        }
        return TRUE;
    }

    /**
     * @param $params
     * @return bool
     * @throws Exception
     */
    protected static function installAdmin($params) {
        self::stdout('[+]: 安装管理员.', Console::FG_GREEN);
        $model = Admin::findOne(1);
        if (!$model) {
            $model = new Admin();
        }
        $model->setAttributes($params);
        $model->gid = Admin::GROUP_ADMIN;
        $model->status = Admin::YES;
        $model->nickname = $model->username;
        $model->password = EncryptHelper::md5($model->password);
        $res = $model->save();
        if (!AppHelper::isOk($res)) {
            self::stdout("安装管理员失败. {$res['msg']}", Console::FG_BLACK);
            return FALSE;
        }
        self::stdout("APP_KEY: " . APP_KEY);
        self::stdout("管理员账号: {$model->username}");
        self::stdout("管理员密码: {$params['password']}");
        return TRUE;
    }

    public static function install($params) {
        try {
            self::connection($params['db']);

            $a = self::installSql($params['db']);
            $b = self::installLocalFile($params['env']);
            $c = self::installAdmin($params['user']);
            $d = self::init_db_file($params['db']);
            if ($a && $b && $c && $d) {
                return AppHelper::success([], 'Install Success.');
            }
            return AppHelper::error('Install Fail.');
        } catch (\Exception $e) {
            return AppHelper::error($e->getMessage(), AppHelper::ERROR_CODE, [$e->getFile(), $e->getLine()]);
        }
    }

    /**
     * @param $params
     * @throws InvalidConfigException
     */
    protected static function connection($params) {
        $data = [
            'class' => 'yii\db\Connection',
            'dsn' => "mysql:host={$params['db_host']};port={$params['db_port']};dbname={$params['db_name']}",
            'username' => $params['db_user'],
            'password' => $params['db_pass'],
            'charset' => 'utf8mb4',
            'tablePrefix' => $params['db_prefix']
        ];
        Yii::$app->set('db', $data);
    }

    protected static function init_db_file($params) {
        $db_file = RUNTIME_ROOT . '/config/db.php';
        $string = <<<EOF
<?php    
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host={$params["db_host"]};port={$params["db_port"]};dbname={$params["db_name"]}',
    'username' => '{$params["db_user"]}',
    'password' => '{$params["db_pass"]}',
    'charset' => 'utf8mb4',
    'tablePrefix' => '{$params["db_prefix"]}',
    'enableSchemaCache' => true,
    'schemaCacheDuration' => 86400,
    'schemaCache' => 'cache_db_schema'
];
EOF;
        return file_put_contents($db_file, $string);
    }

    protected static function installLocalFile($app_env) {
        $key = strtoupper(md5(uniqid(mt_rand(1000, 9999))));
        defined('APP_KEY') or define('APP_KEY', $key);
        $local_file = RUNTIME_ROOT . '/config/local.php';
        $string = "<?php\n";
        $string .= "defined('APP_KEY') or define('APP_KEY', '{$key}');\n";
        $string .= "defined('YII_ENV') or define('YII_ENV', '{$app_env}');\n";
        $string .= "defined('YII_DEBUG') or define('YII_DEBUG', YII_ENV !== 'prod');\n";
        return file_put_contents($local_file, $string);
    }

    protected static function stdout($string, $color = Console::FG_GREY) {
        $string = Console::ansiFormat("{$string}\n", [$color]);
        return Console::stdout($string);
    }
}